import axios from "axios"
import store from '../store'
import router from '../plugs/router'
import SystemConstants from "../utils/SystemConstants";
import CommonUtils from "../utils/CommonUtils";
import {ElMessage} from "element-plus";

// 请求拦截器
axios.interceptors.request.use(
    config => {
        // 发送请求前做什么
        return config
    },
    error => {
        // 在此定义请求错误需要做什么
        console.log(error)
        return Promise.reject(error)
    }
)

// 响应拦截器
axios.interceptors.response.use(
    response => {
        // console.log(response.config.url);
        if (response.headers['content-disposition']) { //处理下载文件
            return response
        }
        return response
    },
    error => {
        const response = error.response

        // 显示后台返回message
        if (!response) {
            return Promise.reject(error)
        }

        const {data} = response
        if (response.status === 422) {
            // 返回状态码为422则重新登录
            if (data.message === 'Signature has expired') {
                store.dispatch('user/resetToken')
                notification.error({
                    message: '重新登录',
                    description: 'Authorization verification failed'
                })
                setTimeout(() => {
                    if (!store.getters.token) location.reload()
                }, 1000)
                return Promise.reject(error)
            }
        } else if (response.status === 403) {
            if (!store.state.loginPageFlag) {
                // 不在登录页
                let userInfo = store.state.userInfo
                userInfo.name = SystemConstants.defUser.name
                store.dispatch('setUserInfo', userInfo)

                let loginDateTime = userInfo.loginDateTime
                let now = new Date();
                if (CommonUtils.isLoginPage(loginDateTime, now)) {
                    // 登录日期不是同一天，且时间长于1小时, 登录页登录
                    router.push("login")
                    store.dispatch('setLoginDialogFlag', false)
                    store.dispatch('setLoginPageFlag', true)
                } else {
                    // 弹框登录
                    store.dispatch('setLoginDialogFlag', true)
                }
            }
        }

        return Promise.reject(error)
    }
)

export default axios;